<template>
    <div class="upload-page">
      <!-- :auto-upload="false" -->
      <el-dialog
        title="重命名决策模型名称"
        draggable="true"
        v-model="renameDialogVisible"
        width="30%"
        :before-close="handleRenameDialogClose">
        <el-input v-model="newFileName"   @input="validateInput" placeholder="请输入新决策模型名称"></el-input>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="renameDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmRename">确定</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 文件列表 -->
      <el-table
      :data="paginationTableData"
      style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="80">
      </el-table-column>
      <el-table-column
        prop="num"
        label="编号"
        width="150">
      </el-table-column>
      <el-table-column
        prop="id"
        label="决策模型名称"
        width="300">
      </el-table-column>
      <el-table-column
        prop="dataSet"
        label="数据集"
        width="400">
      </el-table-column>
      <el-table-column label="操作" width="350" style="display: flex; justify-content: space-between;">
        <template v-slot:default="scope">
          <div class="button-group">
            <el-button 
            type="danger" 
            size="small" @click="viewTreeDetial(scope.row)">
              查看
            </el-button>
            <el-dropdown trigger="click">
              <span class="el-dropdown-link">
                <i class="el-icon-more">
                  <el-icon><MoreFilled /></el-icon>
                </i>
              </span>
              <template v-slot:dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="visualization(scope.row)">可视化</el-dropdown-item>
                  <el-dropdown-item @click="application(scope.row.id)">应用</el-dropdown-item>
                  <el-dropdown-item @click="downloadFile(scope.row)">下载</el-dropdown-item>
                  <el-dropdown-item @click="renameFile(scope.row)">重命名</el-dropdown-item>
                  <el-dropdown-item @click="deleteTree(scope.row)">删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
      </el-table>
  
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="pageSizes"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalFile">
      </el-pagination>
  
      <!-- 批量删除按钮 -->
      <div class="operation" 
      :data="selectedRows"
      style="display: flex; justify-content: space-between;">
        <div class="batch-delete">
          <el-button
            type="danger"
            size="small"
            @click="deleteTree(selectedRows)">批量删除
          </el-button>
        </div>  
        <div class="generation">
          <el-button
            type="danger"
            size="small"
            @click="goToGenerate">去生成
          </el-button>
        </div>
      </div>
    </div>
  </template>
  
  <script>
import { ElButton, ElTable, ElTableColumn, ElPagination } from 'element-plus';
  
  export default {
    components: {
      ElButton,
      ElTable,
      ElTableColumn,
      ElPagination,
    },
    data() {
      return {
        tableData: [], // 假设这里是你的文件列表数据
        paginationTableData:[],
        selectedRows: [], // 用户选择的文件列表
        currentPage: 1, // 当前页码
        pageSize:10,
        renameDialogVisible: false, // 控制重命名对话框的显示
        newFileName: '', // 新文件名
        currentFile: null, // 当前需要重命名的文件对象
        fileExtension: '',
      };
    },
    methods: {
      handleSelectionChange(val) {
        this.selectedRows = val;
        console.log("handleSelectionChange");
      },
      handleSizeChange(newSize) {
        // 处理每页显示条数变化
        console.log("handleSizeChange");
        this.pageSize = newSize;
        this.currentPage = 1; // 重置到第一页
        this.getPaginationTableData();
      },
      handleCurrentChange(newPage) {
        // 处理页码变化
        console.log("handleCurrentChange");
        this.currentPage = newPage;
        this.getPaginationTableData();
      },
      getPaginationTableData(){
        this.paginationTableData=this.tableData.slice(
          (this.currentPage-1)*this.pageSize,
          this.currentPage*this.pageSize
        );
        this.totalFile=this.tableData.length
      },

      goToGenerate() {
        this.$router.push({ path: '/TreeDetail'});
      },

      renameFile(row){
        this.currentFile = row;
        this.newFileName = row.id; // 初始化对话框中的文件名
        this.renameDialogVisible = true;
      },

      validateInput(modelName) {
        const regex = /[\\?%#&$=]+/g;
        if (regex.test(this[modelName])) {
          this.$message.error('非法字符');
          this[modelName] = this[modelName].replace(regex, '');
        }
      },

      // 确认重命名操作
      async confirmRename() {
        if (!this.newFileName.trim()) {
          this.$message.error('文件名不能为空');
          return;
        }
        // 构造请求数据，这里假设后端需要文件的原名和新名
        const requestData = {
          oldName: this.currentFile.id,
          newName: this.newFileName
        };
        // 直接更新tableData中的文件名，而不是重新获取文件列表
        // 发送重命名请求
        this.$axios.post('http://localhost/api/tree/renameTree', requestData, {
          headers: {        
            'token': sessionStorage.getItem('token')
          }
        }).then(response => {
          if (response.data.success) {
            this.$message.success('文件重命名成功');
            this.renameDialogVisible = false;
            // 直接更新tableData中的文件名，而不是重新获取文件列表
            const fileToRename = this.tableData.find(file => file.id === this.currentFile.id);
            if (fileToRename) {
              fileToRename.id = this.newFileName;
            }
          } else {
            this.$message.error('重命名失败：' + response.data.message);
          }
        }).catch(error => {
          console.error('重命名请求失败', error);
          this.$message.error('重命名失败:' + error);
        });
      },
            // 对话框关闭前的处理
            handleRenameDialogClose() {
        this.renameDialogVisible = false;
      },

      async deleteTree(dataToDelete) {
        const isSingle = !Array.isArray(dataToDelete);
        const dataIdsToDelete = isSingle ? [dataToDelete.id] : dataToDelete.map(row => row.id);
        const params = new URLSearchParams()
        Array.from(dataIdsToDelete).forEach(item => {
          params.append('treeNames', item);
        });
        this.$axios.delete(`http://localhost/api/tree/deleteTree?${params}`,{
        headers: {        
          'token': sessionStorage.getItem('token')
          },
        })
          .then((response) => {
            console.log(response.data);
            if (response.data.data) {
              this.$message.success('决策模型删除成功');
              // 从tableData 移除已删除的文件
              this.fetchFileList()
              if (!isSingle) {
                this.selectedRows = [];
              }
            } else {
              this.$message.error('决策模型删除失败：' + response.data.msg);
            }
          })
          .catch((error) => {
            console.error('决策模型删除失败', error);
            this.$message.error('决策模型删除失败:' + error);
          });
      },
      
      //------新增的功能二-----------------------------------------------------------------------------------新增的功能二-------------

      async application(dataTree) {
        sessionStorage.setItem('treeid', dataTree);
        this.$router.push('/quesionnaire')
      },
      visualization(val){
          this.$router.push({
            path: '/VisualizationOfData',
            query: {
              decisionTreeIdToVisual: val.id,
          }
        });
      },

      viewTreeDetial(val){
        this.$router.push({
          path: '/TreeDetail',
          query: {
            decisionTreeName: val.id,
            dataSet: val.dataSet
        }
      });
      },

      async fetchFileList() {
        this.$axios.get('http://localhost/api/tree/treeList', {
          headers: {
            'token': sessionStorage.getItem('token')
          }
        })
        .then(response => {
          console.log(response.data);
          if (response.data.code === 200) {
            const fileList = response.data.data; // 获取数据数组
            this.tableData = fileList.map((file,index) => ({
              num:index+1,
              id: file.treeName, // 生成一个简单的 id
              dataSet: file.fileName,
            }));
            console.log(this.tableData); // 打印处理后的数据
            this.getPaginationTableData()
          }
        })
        .catch(error => {
          console.error('获取决策模型列表失败', error);
          this.$message.error('获取决策模型列表失败:' + error);
        });
      }
    },
    mounted(){
      this.fetchFileList();
    }
  
  };
  </script>
  
  <style scoped>
  .upload-page {
    margin: 20px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0,0,0,0.1); /* 添加阴影效果 */
  padding: 10px; /* 添加内边距 */
  }
  .batch-delete {
    margin-top: 20px;
    text-align: left;
  }
  .generation{
    margin-top: 20px;
    text-align: right;
  }
  .delete-button{
    margin-top: 20px;
  
  }
  .el-dropdown-link {
    margin-left: 10px;
    margin-top: 5px;
    transform: scale(1.5); /* 将按钮放大1.5倍 */
  
  }
  </style>
  